package com.sisucc.contractmanage.zzz;

import com.spire.doc.Document;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.interfaces.ICompositeObject;
import com.spire.doc.interfaces.IDocumentObject;

import javax.imageio.ImageIO;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author linyuqi
 */
public class ImgMain {
    public static void main(String[] args) throws IOException {
        //加载Word文档
        Document document = new Document();
        document.loadFromFile("/Users/linyuqi/Desktop/离线测试程序使用说明(1).docx");

        //创建Queue对象
        Queue nodes = new LinkedList();
        nodes.add(document);

        //创建List对象
        List images = new ArrayList();

        //遍历文档中的子对象
        while (nodes.size() > 0) {
            ICompositeObject node = (ICompositeObject) nodes.poll();
            for (int i = 0; i < node.getChildObjects().getCount(); i++) {
                IDocumentObject child = node.getChildObjects().get(i);
                if (child instanceof ICompositeObject) {
                    nodes.add((ICompositeObject) child);

                    //获取图片并添加到List
                    if (child.getDocumentObjectType() == DocumentObjectType.Picture) {
                        DocPicture picture = (DocPicture) child;
                        images.add(picture.getImage());
                    }
                }
            }
        }

        //将图片保存为PNG格式文件
        for (int i = 0; i < images.size(); i++) {
            File file = new File(String.format("图片-%d.png", i));
            ImageIO.write((RenderedImage) images.get(i), "PNG", file);
        }

    }
}
